#include "Gp.h"

namespace gp
{
	void ConstantBufferSet::Create(gk::GpuProgramHandle hGpuProgram)
	{
		memset(m_buffers, 0, sizeof(gk::ConstantBuffer) * gk::Constants::MaxConstantTablesPerGpuProgram);
		m_numBuffers = hGpuProgram->m_numConstantTables;

		for (cr::size_t i = 0; i < hGpuProgram->m_numConstantTables; ++i)
		{
			gk::GpuProgramConstantTableHandle hTable = hGpuProgram->m_constantTables[i];
			m_buffers[i].m_hGpuProgramTable = hTable;
			gk::GetDevice()->CreateConstantBuffer(m_buffers[i]);
		}
	}

	void ConstantBufferSet::Release()
	{
		for (cr::size_t i = 0; i < m_numBuffers; ++i)
		{
			gk::GetDevice()->ReleaseConstantBuffer(m_buffers[i]);
		}
	}

	void ConstantBufferSet::Commit(gk::ContextHandle hContext)
	{
		for (cr::size_t i = 0; i < m_numBuffers; ++i)
		{
			hContext->CommitConstantBuffer(m_buffers[i]);
		}
	}

	void ConstantBufferSet::SetConstant(gk::GpuProgramConstantHandle hConstant, gk::TextureHandle hTexture)
	{
		CR_ASSERT(hConstant.IsValid());
		for (cr::size_t i = 0; i < m_numBuffers; ++i)
		{
			if (m_buffers[i].m_hGpuProgramTable->GetConstantByName(hConstant->m_hsName).IsValid())
			{
				m_buffers[i].SetConstant(hConstant, hTexture);
			}
		}
	}

	void ConstantBufferSet::SetConstant(gk::GpuProgramConstantHandle hConstant, float v)
	{
		CR_ASSERT(hConstant.IsValid());
		for (cr::size_t i = 0; i < m_numBuffers; ++i)
		{
			if (m_buffers[i].m_hGpuProgramTable->GetConstantByName(hConstant->m_hsName).IsValid())
			{
				m_buffers[i].SetConstant(hConstant, v);
			}
		}
	}

	void ConstantBufferSet::SetConstant(gk::GpuProgramConstantHandle hConstant, cr::Vec4fRef v)
	{
		CR_ASSERT(hConstant.IsValid());
		for (cr::size_t i = 0; i < m_numBuffers; ++i)
		{
			if (m_buffers[i].m_hGpuProgramTable->GetConstantByName(hConstant->m_hsName).IsValid())
			{
				m_buffers[i].SetConstant(hConstant, v);
			}
		}
	}

	void ConstantBufferSet::SetConstant(gk::GpuProgramConstantHandle hConstant, cr::Matrix4fRef v)
	{
		CR_ASSERT(hConstant.IsValid());
		for (cr::size_t i = 0; i < m_numBuffers; ++i)
		{
			if (m_buffers[i].m_hGpuProgramTable->GetConstantByName(hConstant->m_hsName).IsValid())
			{
				m_buffers[i].SetConstant(hConstant, v);
			}
		}
	}

	void ConstantBufferSet::SetConstant(gk::GpuProgramConstantHandle hConstant, float* v, cr::size_t num)
	{
		CR_ASSERT(hConstant.IsValid());
		for (cr::size_t i = 0; i < m_numBuffers; ++i)
		{
			if (m_buffers[i].m_hGpuProgramTable->GetConstantByName(hConstant->m_hsName).IsValid())
			{
				m_buffers[i].SetConstant(hConstant, v, num);
			}
		}
	}

	void ConstantBufferSet::SetConstant(gk::GpuProgramConstantHandle hConstant, int v)
	{

	}
}